package io.gitee.mingbaobaba.apijson.querycondition.query.conditions;



import io.gitee.mingbaobaba.apijson.querycondition.query.exception.ConditionException;

import java.io.Serializable;
import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.function.Function;

/**
 * <p>通过Function获取字段名工具类</p>
 *
 * @author yingsheng.ye
 * @version 1.0.0
 * @since 2023/5/17 15:06
 */
public class ColumnUtil {
    /**
     * 使Function获取序列化能力
     */
    @FunctionalInterface
    public interface SFunction<T, R> extends Function<T, R>, Serializable {

    }

    public static <T> String getName(SFunction<T, ?> fn) {
        // 从function取出序列化方法
        Method writeReplaceMethod;
        try {
            writeReplaceMethod = fn.getClass().getDeclaredMethod("writeReplace");
        } catch (NoSuchMethodException e) {
            throw new ConditionException(e);
        }

        // 从序列化方法取出序列化的lambda信息
        boolean isAccessible = writeReplaceMethod.isAccessible();
        writeReplaceMethod.setAccessible(true);
        SerializedLambda serializedLambda;
        try {
            serializedLambda = (SerializedLambda) writeReplaceMethod.invoke(fn);
        } catch (IllegalAccessException | InvocationTargetException e) {
            throw new ConditionException(e);
        }
        writeReplaceMethod.setAccessible(isAccessible);

        // 从lambda信息取出method、field、class等
        String fieldName = serializedLambda.getImplMethodName().substring("get".length());
        fieldName = fieldName.replaceFirst(String.valueOf(fieldName.charAt(0)), (String.valueOf(fieldName.charAt(0))).toLowerCase());
        Field field;
        try {
            field = Class.forName(serializedLambda.getImplClass().replace("/", ".")).getDeclaredField(fieldName);
        } catch (ClassNotFoundException | NoSuchFieldException e) {
            throw new ConditionException(e);
        }

        // 从field取出字段名，可以根据实际情况调整
        ApiJsonTableField tableField = field.getAnnotation(ApiJsonTableField.class);
        if (tableField != null && tableField.value().length() > 0) {
            return tableField.value();
        } else {
            return fieldName.replaceAll("[A-Z]", "_$0").toLowerCase();
       }
    }
}
